package utils

import (
	"bytes"
	"compress/flate"
	"compress/gzip"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"strings"

	"github.com/andybalholm/brotli"
)

// ReadRequestBody 读取请求体
func ReadRequestBody(req *http.Request) ([]byte, error) {
	if req.Body == nil {
		return nil, nil
	}

	body, err := io.ReadAll(req.Body)
	if err != nil {
		return nil, fmt.Errorf("读取请求体失败: %w", err)
	}

	// 重新设置请求体，以便后续使用
	req.Body = io.NopCloser(bytes.NewReader(body))

	return body, nil
}

// ReadResponseBody 读取响应体
func ReadResponseBody(resp *http.Response) ([]byte, error) {
	if resp.Body == nil {
		return nil, nil
	}

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, fmt.Errorf("读取响应体失败: %w", err)
	}

	// 重新设置响应体，以便后续使用
	resp.Body = io.NopCloser(bytes.NewReader(body))

	return body, nil
}

// DecompressResponse 解压响应体
func DecompressResponse(body []byte, encoding string) ([]byte, error) {
	switch strings.ToLower(encoding) {
	case "gzip":
		reader, err := gzip.NewReader(bytes.NewReader(body))
		if err != nil {
			return nil, err
		}
		defer reader.Close()
		return io.ReadAll(reader)
	case "deflate":
		reader := flate.NewReader(bytes.NewReader(body))
		defer reader.Close()
		return io.ReadAll(reader)
	case "br":
		reader := brotli.NewReader(bytes.NewReader(body))
		return io.ReadAll(reader)
	default:
		return body, nil
	}
}

// DecompressGzip 解压gzip内容
func DecompressGzip(data []byte) ([]byte, error) {
	reader, err := gzip.NewReader(bytes.NewReader(data))
	if err != nil {
		return nil, fmt.Errorf("创建gzip读取器失败: %w", err)
	}
	defer reader.Close()

	decompressed, err := io.ReadAll(reader)
	if err != nil {
		return nil, fmt.Errorf("解压gzip数据失败: %w", err)
	}

	return decompressed, nil
}

// IsTextContent 判断内容类型是否为文本
func IsTextContent(contentType string) bool {
	textTypes := []string{
		"text/",
		"application/json",
		"application/xml",
		"application/javascript",
		"application/x-javascript",
		"application/x-www-form-urlencoded",
	}

	contentType = strings.ToLower(contentType)
	for _, textType := range textTypes {
		if strings.Contains(contentType, textType) {
			return true
		}
	}

	return false
}

// CleanProxyHeaders 清理代理相关的头部 - 最小化清理，确保透传
func CleanProxyHeaders(headers http.Header) http.Header {
	cleaned := make(http.Header)

	// 只移除必须移除的hop-by-hop头部，保持最小化
	hopByHopHeaders := []string{
		"Proxy-Connection", // 只移除代理专用头部
		"Proxy-Authenticate",
		"Proxy-Authorization",
	}

	for key, values := range headers {
		shouldRemove := false
		for _, hopHeader := range hopByHopHeaders {
			if strings.EqualFold(key, hopHeader) {
				shouldRemove = true
				break
			}
		}

		if !shouldRemove {
			// 完全复制原始头部值
			cleaned[key] = make([]string, len(values))
			copy(cleaned[key], values)
		}
	}

	return cleaned
}

// AddForwardedHeaders 添加X-Forwarded-*头部 - 改为可选，默认不添加以确保透传
func AddForwardedHeaders(req *http.Request, clientIP string) {
	// 注释掉所有X-Forwarded头部的添加，确保完全透传
	// 如果需要调试，可以通过配置开启

	// 不添加任何代理相关头部，确保完全透传
	// X-Forwarded-For
	// if existingXFF := req.Header.Get("X-Forwarded-For"); existingXFF != "" {
	// 	req.Header.Set("X-Forwarded-For", existingXFF+", "+clientIP)
	// } else {
	// 	req.Header.Set("X-Forwarded-For", clientIP)
	// }

	// X-Forwarded-Proto
	// if req.TLS != nil {
	// 	req.Header.Set("X-Forwarded-Proto", "https")
	// } else {
	// 	req.Header.Set("X-Forwarded-Proto", "http")
	// }

	// X-Forwarded-Host
	// if req.Header.Get("X-Forwarded-Host") == "" {
	// 	req.Header.Set("X-Forwarded-Host", req.Host)
	// }
}

// FormatBodyForDisplay 格式化响应体用于显示
func FormatBodyForDisplay(body []byte, contentType string, maxSize int) string {
	if len(body) == 0 {
		return ""
	}

	// 如果内容太大，截断显示
	if len(body) > maxSize {
		if IsTextContent(contentType) {
			return string(body[:maxSize]) + fmt.Sprintf("\n[截断显示，总大小: %d bytes]", len(body))
		} else {
			return fmt.Sprintf("[二进制数据: %d bytes]", len(body))
		}
	}

	// 如果是文本内容，直接返回字符串
	if IsTextContent(contentType) {
		return string(body)
	}

	// 如果是JSON，尝试格式化
	if strings.Contains(strings.ToLower(contentType), "json") {
		var jsonData interface{}
		if err := json.Unmarshal(body, &jsonData); err == nil {
			if formatted, err := json.MarshalIndent(jsonData, "", "  "); err == nil {
				return string(formatted)
			}
		}
	}

	// 其他情况显示为二进制数据
	return fmt.Sprintf("[二进制数据: %d bytes]", len(body))
}

// GetClientIP 获取客户端真实IP
func GetClientIP(req *http.Request) string {
	// 尝试从X-Forwarded-For获取
	if xff := req.Header.Get("X-Forwarded-For"); xff != "" {
		ips := strings.Split(xff, ",")
		if len(ips) > 0 {
			return strings.TrimSpace(ips[0])
		}
	}

	// 尝试从X-Real-IP获取
	if xri := req.Header.Get("X-Real-IP"); xri != "" {
		return strings.TrimSpace(xri)
	}

	// 使用RemoteAddr
	if req.RemoteAddr != "" {
		if idx := strings.LastIndex(req.RemoteAddr, ":"); idx != -1 {
			return req.RemoteAddr[:idx]
		}
		return req.RemoteAddr
	}

	return "unknown"
}

// GetTLSVersion 获取TLS版本字符串
func GetTLSVersion(version uint16) string {
	switch version {
	case 0x0301:
		return "TLS 1.0"
	case 0x0302:
		return "TLS 1.1"
	case 0x0303:
		return "TLS 1.2"
	case 0x0304:
		return "TLS 1.3"
	default:
		return fmt.Sprintf("Unknown TLS version: 0x%04x", version)
	}
}
